package com.application.api;

import com.application.api.entity.ResultEntity;
import com.application.model.DictValue;
import com.application.model.News;
import com.platform.annotation.Controller;
import com.platform.mvc.base.BaseController;
import org.apache.log4j.Logger;

import java.sql.Timestamp;

/**
 * 新闻管理
 */
@Controller("/api/news")
public class NewsApiController extends BaseController {

    @SuppressWarnings("unused")
    private static Logger log = Logger.getLogger(NewsApiController.class);

    public void index() {

        String type = getPara("type");//获取表单域中type的值

        paging(splitPage, News.sqlId_splitPageSelect, News.sqlId_splitPageFrom);

        /*Object extData = splitPage.getExtData();
        page.getList().forEach(news -> {
            news.put("type_name", getNewsType(news.get("type"), news.get("hobby")));
        });*/

        renderOk(splitPage);
    }

    /**
     * @title 新闻详情（路径：/api/news/view/{新闻id}）
     */
    public void view() {
        News news = News.dao.findById(getPara("id", getPara()));

        if (news == null) {
            renderJson(new ResultEntity(404, "数据不存在或已被删除"));
        } else {
            news.put("type_name", getNewsType(news.get("type"), news.get("hobby")));
            renderJson(new ResultEntity(news));
        }
    }

    public void save() {
        News news = getModel(News.class, "news");
        news.setCreate_time(new Timestamp(System.currentTimeMillis()));
        news.setCreate_userid(getCUserId());
        news.save();
        renderOk(null);
    }

    public void update() {
        News news = getModel(News.class, "news");
        news.update();
        renderOk(null);
    }

    public void delete() {
        News.dao.deleteByIds(getPara("ids"));

        renderOk(null);
    }

    private String getNewsType(String type, String hobby) {
        DictValue d = null;
        if ("2".equals(type)) {//技术知识，需要查询子分类
            d = DictValue.dao.findByTypeAndCode(DictValue.type_userHobby, hobby);
        } else {
            d = DictValue.dao.findByTypeAndCode(DictValue.type_news, type);
        }
        return d == null ? "" : d.getValue();
    }

}
